<template>
  <div class="createPost-container">
    <el-dialog title="发布文章" :visible.sync="dialogVisible" @close="closeDialog">
      <el-form :model="form">
        <el-form-item label="文章标题:" :label-width="formLabelWidth">
          <el-input v-model="form.title" autocomplete="off" />
        </el-form-item>
        <el-form-item label="文章内容:" :label-width="formLabelWidth">
          <el-input v-model="contents" type="textarea" disabled :rows="2" placeholder="文章内容" />
        </el-form-item>
        <el-form-item label-width="120px" label="发布时间:" class="postInfo-container-item">
          <el-date-picker v-model="form.displayTime" type="datetime" format="yyyy-MM-dd HH:mm:ss" placeholder="选择时间" />
        </el-form-item>
        <el-form-item label-width="120px" label="文章标签:" class="postInfo-container-item">
          <el-tag v-for="tag in form.tags" :key="tag" closable disable-transitions @close="handleClose(tag)">
            {{ tag }}
          </el-tag>
          <el-popover placement="bottom" :width="400" trigger="click">
            <el-button slot="reference" class="button-new-tag" size="small" @click="getTag">+ New Tag(max:5)</el-button>
            <template v-for="tag in tagS">
              <el-button class="popoverBtn" type="primary" plain @click="setInTags(tag.tagId,tag.tagName)">{{ tag.tagName }}</el-button>
            </template>
          </el-popover>
        </el-form-item>
        <el-form-item label-width="120px" label="发布方式:" class="postInfo-container-item">
          <el-radio-group v-model="form.radio">
            <el-radio :label="1">公开</el-radio>
            <el-radio :label="0">私密</el-radio>
          </el-radio-group>
        </el-form-item>

      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="closeDialog">取 消</el-button>
          <el-button
            type="primary"
            @click="publishArticle"
          >发布</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { createArticle, fetchTags, updateArticle } from '@/api/article'
export default {
  name: 'ArticleForm',
  props: {
    id: {
      type: String,
      default: ''
    },
    dialogFormVisible: {
      type: Boolean,
      default: false
    },
    title: {
      type: String,
      required: true
    },
    content: {
      type: String,
      required: true
    },
    isEdit: {
      type: Boolean,
      required: true
    }
  },
  data() {
    return {
      dialogVisible: false,
      form: {
        articleId: '',
        userId: this.$store.state.user.id,
        title: '',
        textarea: '',
        displayTime: undefined,
        tags: [],
        radio: 1,
        tagsId: []
      },
      tagS: [],
      formLabelWidth: '120px',
      contents: ''
    }
  },
  watch: {
    dialogFormVisible(newVal) {
      this.dialogVisible = newVal
    },
    title(newVal) {
      this.form.title = newVal
    },
    content(newVal) {
      this.form.textarea = newVal
      if (newVal.length > 20) { this.contents = this.form.textarea.substring(0, 20) + '...' } else this.contents = this.form.textarea
    }
  },

  methods: {
    // 关闭对话框，调用父类方法
    closeDialog() {
      this.$emit('closeFormDialog')
    },
    closeThisDialog(status, message) {
      this.$emit('closeChildDialog', status, message)
    },
    // 删除标签
    handleClose(tag) {
      const numbers = this.form.tags.indexOf(tag)
      this.form.tags.splice(numbers, 1)
      this.form.tagsId.splice(numbers, 1)
    },
    // 获取标签库里的标签
    getTag() {
      fetchTags().then(response => {
        const { tags } = response.data
        this.tagS = tags
      })
    },
    // 将选择的标签添加到tags数组中
    setInTags(tagId, tagName) {
      if (this.form.tags.length < 5) {
        if (this.form.tagsId.includes(tagId)) {
          this.$message({
            message: '不可重复添加',
            type: 'warning'
          })
        } else {
          this.form.tagsId.push(tagId)
          this.form.tags.push(tagName)
        }
      }
    },
    rTime(date) {
      const json_date = new Date(date).toJSON()
      return new Date(+new Date(json_date) + 8 * 3600 * 1000).toISOString().replace(/T/g, ' ').replace(/\.[\d]{3}Z/, '')
    },
    // 文章发布
    publishArticle() {
      if (this.form.displayTime === undefined) {
        this.$message({
          message: '请填写时间',
          type: 'warning'
        })
        return
      }
      if (this.form.tags.length === 0) {
        this.$message({
          message: '请至少选择一个标签',
          type: 'warning'
        })
        return
      }
      this.form.displayTime = this.rTime(this.form.displayTime)
      // isEdit为true：处于更新状态
      if (this.isEdit) {
        this.form.articleId = this.id
        console.log(this.form)
        updateArticle(this.id, this.form)
          .then(response => {
            this.closeThisDialog('success', '文章更新成功')
            this.form.tags = []
            this.form.tagsId = []
          })
          .catch(error => {
            this.closeThisDialog('warning', '文章更新失败')
            this.form.tags = []
            this.form.tagsId = []
          })
        this.closeDialog()
      } else {
        createArticle(this.form)
          .then(response => {
            this.closeThisDialog('success', '文章创建成功')
            this.form.tags = []
            this.form.tagsId = []
          })
          .catch(error => {
            this.closeThisDialog('warning', '文章创建失败')
            this.form.tags = []
            this.form.tagsId = []
          })
        this.closeDialog()
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.box-center {
  margin: 0 auto;
  display: table;
}

.text-muted {
  color: #777;
}

.user-profile {
  .user-name {
    font-weight: bold;
  }

  .box-center {
    padding-top: 10px;
  }

  .user-role {
    padding-top: 10px;
    font-weight: 400;
    font-size: 14px;
  }

  .box-social {
    padding-top: 30px;

    .el-table {
      border-top: 1px solid #dfe6ec;
    }
  }

  .user-follow {
    padding-top: 20px;
  }
}

.user-bio {
  margin-top: 20px;
  color: #606266;

  span {
    padding-left: 4px;
  }

  .user-bio-section {
    font-size: 14px;
    padding: 15px 0;

    .user-bio-section-header {
      border-bottom: 1px solid #dfe6ec;
      padding-bottom: 10px;
      margin-bottom: 10px;
      font-weight: bold;
    }
  }
}
</style>
